import utils from './Utils'
import { ElFormItem } from 'element-plus'
import _ from "lodash";
ElFormItem.oldSetup = ElFormItem.setup
ElFormItem.setup = function (__props, o) {
    if (__props.required && _.isEmpty(__props.rules)) {
        let label: String = __props.label as String || ''
        label = (label.endsWith(':') || label.endsWith('：')) ? label.substring(0, label.length - 1) : label
        Object.defineProperty(__props, 'rules', {
            writable: false,
            value: [{ required: true, message: `${label}不能为空`, trigger: ['change', 'blur']}]
        })
    }
    return ElFormItem.oldSetup.apply(this, [__props, o])
}
export const emptyValidator = (rule: any, value: any, callback: any) => {
    if (utils.isEmpty(value)) {
        callback(rule.message)
    } else {
        callback()
    }
}

/**
 * element-plus相关组件处理工具
 */
export class ElementPlus {

    /**
     * el-form-item添加基本属性
     */
    attrFormItem(prop: any, label: any, required = true) {
        const attr: any = {
            prop,
            label
        }
        if (required) {
            attr.rules = [{
                required: true,
                message: `${label}不能为空`,
                validator: emptyValidator
            }]
        }
        return attr
    }
}

export default new ElementPlus()